package com.doris.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doris.manager.dto.LoginRequest;
import com.doris.manager.dto.LoginResponse;
import com.doris.manager.entity.User;
import com.doris.manager.mapper.UserMapper;
import com.doris.manager.service.UserService;
import com.doris.manager.util.JwtUtil;
import com.doris.manager.security.JwtAuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final JwtUtil jwtUtil;
    private final PasswordEncoder passwordEncoder;
    private final JwtAuthenticationProvider jwtAuthenticationProvider;

    public UserServiceImpl(JwtUtil jwtUtil,
                          PasswordEncoder passwordEncoder,
                          JwtAuthenticationProvider jwtAuthenticationProvider) {
        this.jwtUtil = jwtUtil;
        this.passwordEncoder = passwordEncoder;
        this.jwtAuthenticationProvider = jwtAuthenticationProvider;
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        Authentication authentication = jwtAuthenticationProvider.authenticate(
                new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword(), null)
        );

        User user = findByUsername(request.getUsername());
        String token = jwtUtil.generateToken(user.getUsername());

        LoginResponse response = new LoginResponse();
        response.setToken(token);

        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        response.setUserInfo(userInfo);

        return response;
    }

    @Override
    public User findByUsername(String username) {
        return getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }

    @Override
    public void createUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        save(user);
    }

    @Override
    public void updateUser(User user) {
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        updateById(user);
    }

    @Override
    public void deleteUser(Long id) {
        removeById(id);
    }
}